package com.stx.crazyblog.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.stx.crazyblog.dao.UserDao;
import com.stx.crazyblog.entity.User;

/*
 * 添加评论内容的servlet方法
 * */
public class UserAddServlet extends HttpServlet {
	// 保持版本的兼容性，保证在版本升级的时候反序列仍能保证对象的唯一性
	private static final long serialVersionUID = 1l;
	// 初始用户dao对象
	UserDao dao = null;

	// 将初始化dao对象的方法放入init()中去，并且保证dao只能被创造一次
	
	@Override
	public void init() throws ServletException {
		// TODO 自动生成的方法存根
		dao = new UserDao();
	}

	

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 * 
	 * */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 * 
	 * */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// 设定请求编码集为uft-8 防止中文出现乱码
		request.setCharacterEncoding("utf-8");
		
		// 创建用户类数据视图对象（用于封装评论信息查询到的内容）
		User user = new User();
		// 从页面获取新增数据
		user.setUname(request.getParameter("us_uname"));
		user.setBlogname(request.getParameter("us_blogname"));
		user.setPassword(request.getParameter("us_password"));
		
		try {
			// 调用dao中的插入用户数据的方法
			dao.insertUser(user);
			// 将结果保存到request中
			
			request.setAttribute("user", "注册成功");
			// 调用servlet中的查询方法，更新user信息表
			RequestDispatcher rd = getServletContext().getRequestDispatcher(
					"/jsp/login.jsp");
			// 将请求转发给servlet
			rd.forward(request, response);
		} catch (Exception e) {
			// 将结果保存到request中
			e.printStackTrace();
			request.setAttribute("user", "注册失败");
			
			// 调用servlet中的查询方法，更新user信息表
			RequestDispatcher rd = getServletContext().getRequestDispatcher(
					"/jsp/register.jsp");
			// 将请求转发给servlet
			rd.forward(request, response);
		}
	}

}
